﻿/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "sqlcontactmodel.h"

#include <QDateTime>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QSqlQuery>

static const char *contactTableName = "Contacts";

static void createTable()
{
    if (QSqlDatabase::database().tables().contains(contactTableName)) {
        QSqlQuery query;
        query.exec("UPDATE Contacts SET user_online = '0' where user_mail!='GROUP'");
        return;
    }

    QSqlQuery query;
    if (!query.exec(
            "CREATE TABLE IF NOT EXISTS 'Contacts' ("
            "'user_mail' TEXT NOT NULL,"
            "'user_name' TEXT NOT NULL,"
            "'user_pwd' TEXT NOT NULL,"
            "'user_img' TEXT NOT NULL,"
            "'user_online' TEXT NOT NULL,"
            "'user_online_time' TEXT NOT NULL,"
            "'user_messages' TEXT NOT NULL,"
            "   PRIMARY KEY(user_mail)"
            ")")) {
        qFatal("Failed to query database: %s", qPrintable(query.lastError().text()));
    }
    query.exec("INSERT INTO Contacts VALUES('GROUP','GROUP','','group','1','2099-01-01T12:00:00','0')");
    //    query.exec("INSERT INTO Conversations VALUES('Me', 'Ernest Hemingway', '2016-01-07T14:36:06', 'Hello!')");
}

SqlContactModel::SqlContactModel(QObject *parent) :
    QSqlTableModel(parent),m_currentIndex(0)
{
    createTable();
    setTable(contactTableName);
    setSort(5, Qt::DescendingOrder);
    // Ensures that the model is sorted correctly after submitting a new row.
    setEditStrategy(QSqlTableModel::OnManualSubmit);
}

QString SqlContactModel::recipient() const
{
    return m_recipient;
}

void SqlContactModel::setRecipient(const QString &recipient)
{
    if (recipient == m_recipient)
        return;

    m_recipient = recipient;

    QString filterString = QString::fromLatin1("(%1)").arg(recipient);
    //    if(recipient == "GROUP"){
    //        filterString = QString::fromLatin1("(recipient = '%1')").arg(m_recipient);
    //    }
    //    else{
    //        filterString = QString::fromLatin1(
    //                           "(recipient = '%1' AND author = '%2') OR (recipient = '%3' AND author='%4')").arg(m_recipient).arg(m_meMail).arg(m_meMail).arg(m_recipient);
    //    }

    qDebug()<<filterString;
    setFilter(filterString);
    select();

    emit recipientChanged();
}

void SqlContactModel::setCurrentIndex(int n){
    //    qDebug()<<n<<rowCount();
    //    QSqlRecord mrecord = record(n);

    //    qDebug()<<mrecord.count()<<mrecord.value("user_mail");
    m_currentIndex = n;
    emit currentIndexChanged();
}

QVariant SqlContactModel::data(const QModelIndex &index, int role) const
{
    if (role < Qt::UserRole)
        return QSqlTableModel::data(index, role);

    const QSqlRecord sqlRecord = record(index.row());
    return sqlRecord.value(role - Qt::UserRole);
}

QHash<int, QByteArray> SqlContactModel::roleNames() const
{
    QHash<int, QByteArray> names;
    names[Qt::UserRole] = "user_mail";
    names[Qt::UserRole + 1] = "user_name";
    names[Qt::UserRole + 2] = "user_pwd";
    names[Qt::UserRole + 3] = "user_img";
    names[Qt::UserRole + 4] = "user_online";
    names[Qt::UserRole + 5] = "user_online_time";
    names[Qt::UserRole + 6] = "user_messages";
    return names;
}

void SqlContactModel::clearMessageSum(int index)
{
    QSqlRecord mrecord = record(index);
    if(mrecord.value("user_messages").toInt()){
        mrecord.setValue("user_messages","0");
        setRecord(index, mrecord);
        submitAll();
    }
}

void SqlContactModel::getNewMessage(QString from)
{
    const QString timestamp = QDateTime::currentDateTime().toString(Qt::ISODate);

    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord lrecord = record(i);
        QString temp = lrecord.value("user_mail").toString();
        QString sum = lrecord.value("user_messages").toString();
        if (temp==from)
        {
            QString mail;
            if(m_currentIndex>0){
                QSqlRecord mrecord = record(m_currentIndex);
                mail = mrecord.value("user_mail").toString();
            }
            if(from!="GROUP")
                lrecord.setValue("user_online_time",timestamp);
//            if(i!=m_currentIndex)
            lrecord.setValue("user_messages",QString("%1").arg(sum.toInt()+1));
            setRecord(i, lrecord);
            submitAll();
            //            select();
            if(m_currentIndex>0){
                for (int i = 0; i < rowCount(); ++i)
                {
                    QSqlRecord xrecord = record(i);
                    if(xrecord.value("user_mail").toString()==mail){
                        setCurrentIndex(i);
                    }
                }
            }
            emit sendNewMessage();
            break;
        }
    }
}

void SqlContactModel::newUserOffline(QString mail)
{
    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord lrecord = record(i);
        QString temp = lrecord.value("user_mail").toString();

        if (temp==mail)
        {
            lrecord.setValue("user_online","0");
            setRecord(i, lrecord);
            submitAll();
            break;
        }
    }
}

void SqlContactModel::allUserOffline()
{
    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord lrecord = record(i);
        QString temp = lrecord.value("user_mail").toString();

        if (temp!="GROUP")
        {
            lrecord.setValue("user_online","0");
            setRecord(i, lrecord);
        }
    }
    submitAll();
}

QString SqlContactModel::getMailImg(QString mail)
{
    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord lrecord = record(i);
        QString temp = lrecord.value("user_mail").toString();

        if (temp==mail)
        {
            return lrecord.value("user_img").toString();
        }
    }
    return "";
}

QString SqlContactModel::getMailName(QString mail)
{
    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord lrecord = record(i);
        QString temp = lrecord.value("user_mail").toString();

        if (temp==mail)
        {
            return lrecord.value("user_name").toString();
        }
    }
    return "";
}

void SqlContactModel::sendToSql(QJsonObject value)
{
    const QString timestamp = QDateTime::currentDateTime().toString(Qt::ISODate);

    for (int i = 0; i < rowCount(); ++i)
    {
        QSqlRecord newRecord = record(i);
        QString temp = newRecord.value("user_mail").toString();

        if (temp==value["user_mail"].toString())
        {
            QString mail;
            if(m_currentIndex>0){
                QSqlRecord mrecord = record(m_currentIndex);
                mail = mrecord.value("user_mail").toString();
            }
            newRecord.setValue("user_mail", value["user_mail"].toString());
            newRecord.setValue("user_name", value["user_name"].toString());
            newRecord.setValue("user_pwd", "");
            newRecord.setValue("user_img", value["user_img"].toString());
            newRecord.setValue("user_online", "1");
            newRecord.setValue("user_online_time", timestamp);

            setRecord(i, newRecord);
            submitAll();
            if(m_currentIndex>0){
                for (int i = 0; i < rowCount(); ++i)
                {
                    QSqlRecord xrecord = record(i);
                    if(xrecord.value("user_mail").toString()==mail){
                        setCurrentIndex(i);
                    }
                }

            }
            return;
        }
    }
    QString mail;
    if(m_currentIndex>0){
        QSqlRecord mrecord = record(m_currentIndex);
        mail = mrecord.value("user_mail").toString();
    }
    QSqlRecord newRecord = record();
    newRecord.setValue("user_mail", value["user_mail"].toString());
    newRecord.setValue("user_name", value["user_name"].toString());
    newRecord.setValue("user_pwd", "");
    newRecord.setValue("user_img", value["user_img"].toString());
    newRecord.setValue("user_online", "1");
    newRecord.setValue("user_online_time", timestamp);
    newRecord.setValue("user_messages", "0");
    if (!insertRecord(rowCount(), newRecord)) {
        qWarning() << "Failed to send message:" << lastError().text();
        return;
    }
    submitAll();
    if(m_currentIndex>0){
        for (int i = 0; i < rowCount(); ++i)
        {
            QSqlRecord xrecord = record(i);
            if(xrecord.value("user_mail").toString()==mail){
                setCurrentIndex(i);
            }
        }

    }
}

void SqlContactModel::updateCurrentUserMail(QString mail)
{
    if(mail.isEmpty()){
        qWarning()<<"mail is Empty!";
        return;
    }
    setCurrentIndex(0);
    m_currentUserMail = mail;
    setRecipient(QString("user_mail != '%1'").arg(m_currentUserMail));
}
